﻿using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json.Linq;
using OfficeOpenXml;

namespace Solution.Application.Utils
{
    public class ExcelHelper
    {
        public static List<T> ReadExcel<T>(string fileName) where T : class
        {
            if (string.IsNullOrEmpty(fileName) || !File.Exists(fileName))
            {
                return default;
            }

            JArray ja = new JArray();
            using (var fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (var package = new ExcelPackage(fs))
                {
                    var sheet = package.Workbook.Worksheets[1];
                    for (int row = 2; row <= sheet.Dimension.End.Row; row++)
                    {
                        JObject json = new JObject();
                        for (int col = sheet.Dimension.Start.Column; col <= sheet.Dimension.End.Column; col++)
                        {
                            object p = sheet.GetValue(sheet.Dimension.Start.Row, col);
                            string propertyName = p == null ? string.Empty : p.ToString().Trim();
                            object v = sheet.GetValue(row, col);
                            string value = v == null ? string.Empty : v.ToString().Trim();
                            if (!propertyName.Equals(string.Empty))
                            {
                                if (typeof(T).GetProperties().Length <= 1 && value.Equals(string.Empty))
                                {
                                    continue;
                                }
                                json.Add(propertyName, value);
                            }
                        }
                        if (json.Count > 0)
                        {
                            ja.Add(json);
                        }
                    }
                    fs.Close();
                    return ja.ToObject<List<T>>();
                }
            }
        }
    }
}